package com.yuancheng.modules.msapp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yuancheng.common.api.vo.Result;
import com.yuancheng.common.constant.CommonConstant;
import com.yuancheng.common.util.*;
import com.yuancheng.modules.msweb.entity.Operator;
import com.yuancheng.modules.msweb.service.IDeviceInfoService;
import com.yuancheng.modules.msweb.service.IEventInfoService;
import com.yuancheng.modules.msweb.service.IOperatorService;
import com.yuancheng.modules.shiro.authc.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户接口
 */
@RestController
@RequestMapping("/msapp/")
@Slf4j
public class MsOperatorController {

    @Autowired
    private IOperatorService operatorService;
    @Autowired
    private IDeviceInfoService deviceInfoService;
    @Autowired
    private IEventInfoService eventInfoService;
    @Autowired
    private RedisUtil redisUtil;


    /**
     * 用户登录
     * @param params
     * @param request
     * @return
     */
    @PostMapping("userLogin")
    public Result userLogin(@RequestBody String params, HttpServletRequest request)throws Exception{

        Result<Map<String, Object>> result = new Result<Map<String, Object>>();
        //接收前端入参
        String userAccount = JacksonUtil.parseString(params,"userAccount");
        String userPassword = JacksonUtil.parseString(params,"userPassword");
        if(StringUtil.isEmpty(userAccount) || StringUtil.isEmpty(userPassword)){
            return  result.error(101,"参数不能为空");
        }
        if (!StringUtil.isPhone(userAccount)) {
            return  result.error(201,"手机号格式不正确");
        }

        QueryWrapper<Operator> userWrapper = new QueryWrapper<>();
        userWrapper.eq("phone",userAccount);
        Operator operator = operatorService.getOne(userWrapper);
        if(operator==null){
            return result.error(301,"该用户不存在!");
        }else{
            //密码验证
            String password = new SimpleHash("SHA-1", userAccount, userPassword).toString();
            String appuserPassword = operator.getPsw();
            if(!appuserPassword.equals(password)){
                result.error500("用户名或密码错误");
                return result;
            }
            //生成token
            String token = JwtUtil.sign(userAccount, appuserPassword);
            redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
            redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
            Map<String, Object> map = new HashMap<>();
            map.put("operatorInfo",operator);
            result.setMessage("登录成功");
            result.setResult(map);
            result.setSuccess(true);
        }
        return result;
    }


    /**
     * 获取手机验证码
     * @param params
     * @return
     */
    @PostMapping("getMsgCode")
    public Result getCode(@RequestBody String params, HttpServletRequest request){
        Result<Map<String, Object>> result = new Result<Map<String, Object>>();
        //接受前端入参
        String userAccount = JacksonUtil.parseString(params, "userAccount");

        if (StringUtil.isEmpty(userAccount)) {
            return  result.error(101,"参数不能为空");
        }
        if (!StringUtil.isPhone(userAccount)) {
            return  result.error(201,"手机号格式不正确");
        }
        // 根据手机号查询用户信息
        QueryWrapper<Operator> userWrapper = new QueryWrapper<>();
        userWrapper.eq("phone",userAccount);
        Operator operator = operatorService.getOne(userWrapper);
        if(operator==null){
            return result.error(301,"该用户不存在!");
        }
        // 生成随机数发送验证码
        String code = RandomUtil.getRandom(4, RandomUtil.TYPE_NUMBER);
        boolean isSuccess = SmsUtil.sendSms(userAccount,code);
        if(isSuccess){
            if(!redisUtil.set( userAccount+code,code, CommonConstant.CODE_EXPIRE_TIME)){
                log.info(userAccount + "发送验证码[" + code + "]成功，保存至缓存失败");
            }
            Map<String, Object> data = new HashMap<>();
            result.setResult(data);
            result.setSuccess(true);
            result.setMessage("验证码发送成功");
            return result;
        }else{
            return  result.error(401,"验证码发送失败");
        }
    }

    /**
     * 更改登录密码
     * @param params
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("editPassword")
    public Result editPassword(@RequestBody String params, HttpServletRequest request)throws Exception {
        Result<Map<String, Object>> result = new Result<Map<String, Object>>();

        //接收前端入参
        String userAccount = JacksonUtil.parseString(params,"userAccount");
        String code = JacksonUtil.parseString(params,"code");
        String userPassword = JacksonUtil.parseString(params,"userPassword");

        if(StringUtil.isEmpty(userAccount) || StringUtil.isEmpty(code) || StringUtil.isEmpty(userPassword)){
            return  result.error(101,"参数不能为空");
        }

        if (!StringUtil.isPhone(userAccount)) {
            return  result.error(201,"手机号格式不正确");
        }
        QueryWrapper<Operator> userrWrapper = new QueryWrapper<>();
        userrWrapper.eq("phone",userAccount);
        Operator operator = operatorService.getOne(userrWrapper);
        if(operator==null){
            return result.error(301,"该用户不存在!");
        }
        String redisCode = redisUtil.get(userAccount+code).toString();
        if(code.equals(redisCode)){
            userPassword = new SimpleHash("SHA-1", userAccount, userPassword).toString();
            operator.setPsw(userPassword);
             boolean  isSuccess= operatorService.updateById(operator);
            if(isSuccess){
                result.setMessage("密码修改成功!");
                Map<String, Object> data = new HashMap<>();
                result.setResult(data);
                result.setSuccess(true);
                return result;
            }else {
                return result.error(302,"密码修改失败!");
            }
        }else{
            return result.error(301," 验证码不正确或已过期");
        }
    }


    /**
     * 获取终端列表
     * @param params
     * @return
     */
    @PostMapping("queryDeviceList")
    public Result queryDeviceList(@RequestBody String params, HttpServletRequest request){
        Result<List<Map<String, String>>> result = new Result<>();
        //接受前端入参
        String operatorId = JacksonUtil.parseString(params, "operatorId");
        String deviceName = JacksonUtil.parseString(params, "deviceName");
        Integer pageNo = JacksonUtil.parseInteger(params, "pageNo");
        Integer pageSize = JacksonUtil.parseInteger(params, "pageSize");

        if (StringUtil.isEmpty(operatorId) || StringUtil.isEmpty(pageNo.toString()) || StringUtil.isEmpty(pageSize.toString())) {
            return  result.error(101,"参数不能为空");
        }

        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("operatorId",operatorId);
        paramMap.put("devname",deviceName);
        paramMap.put("pageNo",pageNo);
        paramMap.put("pageSize",pageSize);

        List<Map<String,String>> deviceList = deviceInfoService.queryDeviceList(paramMap);
        result.setSuccess(true);
        result.setResult(deviceList);
        return result;
    }


    /**
     * 获取事件列表
     * @param params
     * @return
     */
    @PostMapping("queryEventList")
    public Result queryEventList(@RequestBody String params, HttpServletRequest request){
        Result<List<Map<String, String>>> result = new Result<>();
        //接受前端入参
        String devnum = JacksonUtil.parseString(params, "devnum");
        Integer pageNo = JacksonUtil.parseInteger(params, "pageNo");
        Integer pageSize = JacksonUtil.parseInteger(params, "pageSize");

        if (StringUtil.isEmpty(devnum) || StringUtil.isEmpty(pageNo.toString()) || StringUtil.isEmpty(pageSize.toString())) {
            return  result.error(101,"参数不能为空");
        }

        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("devnum",devnum);
        paramMap.put("pageNo",pageNo);
        paramMap.put("pageSize",pageSize);

        List<Map<String,String>> eventList = deviceInfoService.queryEventList(paramMap);
        result.setSuccess(true);
        result.setResult(eventList);
        return result;
    }


    /**
     * 获取设备详情
     * @param params
     * @return
     */
    @PostMapping("queryDeviceDetail")
    public Result queryDeviceDetail(@RequestBody String params, HttpServletRequest request){
        Result<List<Map<String, String>>> result = new Result<>();
        //接受前端入参
        String devnum = JacksonUtil.parseString(params, "devnum");

        if (StringUtil.isEmpty(devnum)) {
            return  result.error(101,"参数不能为空");
        }

//        QueryWrapper<EventInfo> wrapper = new QueryWrapper<>();
//        wrapper.eq("devnum",devnum);
//        wrapper.eq("readstate","1");
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("devnum",devnum);
        paramMap.put("readstate","2");
        eventInfoService.updateReadState(paramMap);

//        List<EventInfo> eventList = eventInfoService.list(wrapper);
//        if(eventList!=null && eventList.size()>0){
//            for(int i=0;i<eventList.size();i++){
//                eventList.get(i).setReadstate("2");
//                eventInfoService.updateById(eventList.get(i));
//            }
//        }
        // 使用 updateBatchById 会报错，原因未知，具体错误：
        // updateBatch Parameter 'param1' not found. Available parameters are
        // [et]
        //eventInfoService.updateBatchById(eventList);

        result.setSuccess(true);
        return result;
    }






}